package com.wutong.eams.service;

import com.wutong.eams.dto.AuthenticDTO;
import com.wutong.eams.entity.User;
import com.wutong.eams.enums.Role;
import com.wutong.eams.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class UserAuthenticService implements IService<UserMapper, User> {

    public UserMapper userMapper = new UserMapper() {};

    @Override
    public UserMapper getMapper() {
        return userMapper;
    }

    public User login(AuthenticDTO.LoginDTO dto) {
        List<User> users = getMapper().selectByUsername(dto.getUsername());
        if (users.size() != 1) {
            log.debug("检索到 {} 个用户，结果非法", users.size());
            return null;
        } else {
            log.info("用户 {} 登录成功", users.getFirst().getUsername());
            return users.getFirst();
        }
    }

    public boolean isMatchRole(String username, Role role) {
        String requiredRole;
        List<User> result = getMapper().selectByUsername(username);
        if (result.size() != 1) {
            log.debug("检索到 {} 个角色，结果非法", result.size());
            return false;
        } else {
            requiredRole = result.getFirst().getRole();
            return requiredRole.equals(role.getRoleName());
        }
    }

    public User getUserInfo(String username) {
        List<User> users = getMapper().selectByUsername(username);
        if (users.size() != 1) {
            log.debug("检索到多余 {} 个用户，结果非法", users.size() - 1);
            return null;
        } else {
            log.info("获取用户 {} 的信息成功", users.getFirst().getUsername());
            return users.getFirst();
        }
    }


}